﻿using BST250301;
using BST250301TestStand.Models;
using CsvHelper;
using HarfBuzzSharp;
using Microsoft.EntityFrameworkCore.Query.Internal;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static BST250301TestStand.Models.Utils.TCUConfig;

namespace BST250301TestStand.Models.Utils
{
    internal class NVHConfig
    {
        internal static TCP NVHClient = null;
        public static string IPStr { get; set; }
        public static int Port { get; set; }
        public bool IsConnected { get; set; }
        public static string LastID { get; set; }
        public static string RemotePLCtype { get; set; }
        public static string RemotePLCaddress { get; set; }

        private static ShowNVHStatusParm _nvh_status = new ShowNVHStatusParm();
        public static event EventHandler<ShowNVHStatusParm> ShowNVHStatus;
        internal static bool ConnectNVH()
        {
            try
            {
                NVHClient = new TCP(IPStr, Port);
                NVHClient.DataReceived += async (sender, data) =>
                {
                    _nvh_status.IsOnline = true;
                    if (!data.Contains("HeatBeatSend"))
                    {
                       await ExplanStr(data);
                    }
                    // MessageBox.Show($"主程序收到数据: {data}");
                };
                NVHClient.Disconnected += (sender, e) =>
                {
                    _nvh_status.IsOnline = false;
                    ShowNVHStatus?.Invoke(null, _nvh_status);
                    MessageBox.Show("NVH已断开连接");
                };
                NVHClient.ConnectAsync();
                _nvh_status.IsOnline = true;
                ShowNVHStatus?.Invoke(null, _nvh_status);
                //Task.Run(()=> HeatBeatSend());

                return true;

                NVHClient.SendAsync("\\00\\00\\00\\06$A#");//\00\00\00\06$A#
                Thread.Sleep(3000);
                NVHClient.Disconnect();
            }
            catch (Exception)
            {
                _nvh_status.IsOnline = false;
                return false;
            }
        }
        static async Task ExplanStr(string asciistr)
        {
            try
            {
                var nvh = new ShowNVHStatusParm();
                nvh.IsOnline = true;
                nvh.DataStr = asciistr;
                nvh.ListChn1 = new ChannelData();
                nvh.ListChn2 = new ChannelData();
                nvh.ListChn3 = new ChannelData();
                nvh.ListChn4 = new ChannelData();

                var getstr = ParseResponse(asciistr);//.Replace("\r\n", "");//.Replace("\n", "");
                if (!string.IsNullOrEmpty(getstr))
                {
                    //?$A_over^Result:'NG',Status:'NG',???????? ????-??????????????????-CH1_Max_Checked Single Value:'NG',???????? ????-??????????????????-CH3_Max_Checked Single Value:'NG',???????? ????-??????????????????-CH4_Max_Checked Single Value:'NG'^OK#
                    if (getstr.Contains("$A_over^Result"))
                    {
                        string patternMain = @"Result:'(?<Result>\w+)',Status:'(?<Status>\w+)'";
                        Match m = Regex.Match(getstr, patternMain);

                        nvh.Result = m.Groups["Result"].Value;
                        nvh.Status = m.Groups["Status"].Value;

                        string patternCH = @"CH(?<ch>\d+)_Max_Checked Single Value:'(?<val>\w+)'";
                        foreach (Match mc in Regex.Matches(getstr, patternCH))
                        {
                            if (mc.Value.Contains("CH1"))
                                nvh.ListChn1.Max_Checked_Single_Value = mc.Groups["val"].Value;
                            else if (mc.Value.Contains("CH2"))
                                nvh.ListChn2.Max_Checked_Single_Value = mc.Groups["val"].Value;
                            else if (mc.Value.Contains("CH3"))
                                nvh.ListChn3.Max_Checked_Single_Value = mc.Groups["val"].Value;
                            else if (mc.Value.Contains("CH4"))
                                nvh.ListChn4.Max_Checked_Single_Value = mc.Groups["val"].Value;
                        }
                    }
                    if (getstr.Contains("?$^data^") && getstr.Contains("Transmit Identification"))
                    {
                        nvh.TestID = Regex.Match(getstr, @"Transmit Identification:(.{2})").Groups[1].Value;
                        if (!string.IsNullOrEmpty(nvh.TestID))
                            LastID = nvh.TestID;
                        string pattern = @"Data Info:.*?(?<Channel>CH\d+)_Max_Checked.*?"
                                       + @"Test Result:(?<Result>\w+).*?"
                                       + @"Data:\s*\{\s*(?<Data>[\d\.\-]+)\s*\}.*?"
                                       + @"Upper Limit:\s*(?<UpperLimit>[\d\.\-]+)"
                                       + @".*?#";

                        var matches = Regex.Matches(getstr, pattern, RegexOptions.Singleline);
                        if (matches.Count == 0)
                        {
                            pattern = @"Test Result:(?<Result>\w+).*?"
                                           + @"Data:\s*\{\s*(?<Data>[\d\.\-]+)\s*\}.*?"
                                           + @"Upper Limit:\s*(?<UpperLimit>[\d\.\-]+)"
                                           + @".*?#";

                            matches = Regex.Matches(getstr, pattern, RegexOptions.Singleline);
                        }
                        if (matches.Count == 0)
                        {
                            pattern = @"Transmit Identification:(?<Identification>\S+).*?" +
                                        @"Test Result:(?<Result>.+?)\s*Data:\s*\{\s*(?<Data>[^}]+)\s*\}.*?" +
                                        @"Limit:\s*\{\s*(?<Limit>[^}]+)\s*\}";

                            matches = Regex.Matches(getstr, pattern, RegexOptions.Singleline);
                        }

                        foreach (Match mc in matches)
                        {
                            if (mc.Groups["Channel"].Value.Contains("CH1"))
                            {
                                nvh.ListChn1.Channel = mc.Groups["Channel"].Value;
                                nvh.ListChn1.Data = mc.Groups["Data"].Value;
                                nvh.ListChn1.Result = mc.Groups["Result"].Value;
                                nvh.ListChn1.UpperLimit = mc.Groups["UpperLimit"].Value;
                            }
                            else if (mc.Groups["Channel"].Value.Contains("CH2"))
                            {
                                nvh.ListChn2.Channel = mc.Groups["Channel"].Value;
                                nvh.ListChn2.Data = mc.Groups["Data"].Value;
                                nvh.ListChn2.Result = mc.Groups["Result"].Value;
                                nvh.ListChn2.UpperLimit = mc.Groups["UpperLimit"].Value;

                            }
                            else if (mc.Groups["Channel"].Value.Contains("CH3"))
                            {
                                nvh.ListChn3.Channel = mc.Groups["Channel"].Value;
                                nvh.ListChn3.Data = mc.Groups["Data"].Value;
                                nvh.ListChn3.Result = mc.Groups["Result"].Value;
                                nvh.ListChn3.UpperLimit = mc.Groups["UpperLimit"].Value;

                            }
                            else if (mc.Groups["Channel"].Value.Contains("CH4"))
                            {
                                nvh.ListChn4.Channel = mc.Groups["Channel"].Value;
                                nvh.ListChn4.Data = mc.Groups["Data"].Value;
                                nvh.ListChn4.Result = mc.Groups["Result"].Value;
                                nvh.ListChn4.UpperLimit = mc.Groups["UpperLimit"].Value;

                            }
                        }
                    }
                }
                if (nvh.TestID == null)
                    nvh.TestID = LastID;
                _nvh_status = nvh;
            }
            catch (Exception)
            {
            }

            ShowNVHStatus?.Invoke(null, _nvh_status);
            // MessageBox.Show($"主程序收到数据: {data}");
        }

        internal static async Task HeatBeatSend()
        {
            while (isRunning)
            {
                Thread.Sleep(3000);
                try
                {
                    var ret = await NVHClient.SendAsync("HeatBeatSend");
                    _nvh_status.IsOnline = ret;
                }
                catch (Exception)
                {
                    _nvh_status.IsOnline = false;
                }
                ShowNVHStatus?.Invoke(null, _nvh_status);
            }
        }
        internal static async Task SetSNTest(string sn, string test)
        {
            var ret = await NVHClient.SendAsync($"\\00\\00\\00\\06$A#");
        }

        public static string ParseResponse(string rawString)
        {
            if (string.IsNullOrEmpty(rawString))
            {
                return null;
            }

            // 1. 清理控制字符（\00, \0A, \0D）
            // \0D (CR, 回车), \0A (LF, 换行), \00 (Null)
            // 使用 Trim() 清理头部和尾部的空白和空字符（如果存在）
            string cleanString = rawString.Trim(new char[] { '\r', '\n', '\0' });

            // 示例：移除字符串内部的 Null 字符（如果协议不要求保留）
            cleanString = cleanString.Replace("\0", string.Empty);

            if (string.IsNullOrEmpty(cleanString))
            {
                return null;
            }
            return cleanString;
        }
        public static NVHCHData GetSetNVHData(string sn, DateTime dt)
        {
            var nvh = new NVHCHData();
            try
            {
                string filename = GetNVHDataFileName(sn, dt);
                using var reader = new StreamReader(filename);
                using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
                var result = csv.Read();
                int rows = 0;
                while (csv.Read())
                {
                    rows++;
                    if (rows == 1)
                        nvh.DT = csv.GetField<string>(0);
                    if (rows == 4)
                        nvh.Reult = csv.GetField<string>(1);
                    if (rows == 9)
                        nvh.SN = csv.GetField<string>(1).TrimEnd('\t');
                    if (rows == 13)
                        nvh.TestID = csv.GetField<string>(1).TrimEnd('\t');
                    if (rows == 37)
                        nvh.CH1DBAVG = csv.GetField<string>(1);
                    if (rows == 41)
                        nvh.CH2DBAVG = csv.GetField<string>(1);
                    if (rows == 45)
                        nvh.CH3VibrationAVG = csv.GetField<string>(1);
                    if (rows == 49)
                        nvh.CH4VibrationAVG = csv.GetField<string>(1);
                    if (rows == 52)
                        nvh.CH1DBMaxResult = csv.GetField<string>(1);
                    if (rows == 53)
                        nvh.CH1DBMax = csv.GetField<string>(1);
                    if (rows == 56)
                        nvh.CH2DBMaxResult = csv.GetField<string>(1);
                    if (rows == 57)
                        nvh.CH2DBMax = csv.GetField<string>(1);
                    if (rows == 60)
                        nvh.CH3VibrationMaxResult = csv.GetField<string>(1);
                    if (rows == 61)
                        nvh.CH3VibrationMax = csv.GetField<string>(1);
                    if (rows == 64)
                        nvh.CH4VibrationMaxResult = csv.GetField<string>(1);
                    if (rows == 65)
                        nvh.CH4VibrationMax = csv.GetField<string>(1);
                }
            }
            catch (Exception)
            {
            }
            return nvh;
        }
        /// <summary>
        /// 寻找文件
        /// </summary>
        /// <param name="sn"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        private static string GetNVHDataFileName(string sn, DateTime dt)
        {
      
            string directoryPath = MainWindow.configapp.NVHPath+$"{dt.ToString("yyyyMMdd")}\\";
            string searchPattern = $"{sn}_{dt.ToString("yyyyMMdd")}*"; // 包含"keyword"的文件20251101142842_NG
            try
            {
                string[] files = Directory.GetFiles(directoryPath, searchPattern);
                if (files.Length == 0)
                {
                    int ws = 60;
                    while (ws > 0)
                    {
                        ws--;
                        Task.Delay(500);
                        files = Directory.GetFiles(directoryPath, searchPattern);
                        if (files.Length == 0)
                            return Path.GetFullPath(files.Last());
                    }
                }
                else
                {
                    return Path.GetFullPath(files.Last());
                }
            }
            catch (Exception ex)
            {
            }
            return null;
        }
    }
    /// <summary>
    /// 噪音检测
    /// </summary>
    public class ShowNVHStatusParm
    {
        public ChannelData ListChn1 { get; set; }
        public ChannelData ListChn2 { get; set; }
        public ChannelData ListChn3 { get; set; }
        public ChannelData ListChn4 { get; set; }
        /// <summary>
        /// 在线状态
        /// </summary>
        public bool IsOnline { get; set; }
        /// <summary>
        /// 检测总结果
        /// </summary>
        public string Result { get; set; }
        /// <summary>
        /// 检测时间
        /// </summary>
        public string DT { get; set; }
        /// <summary>
        /// SN
        /// </summary>
        public string SN { get; set; }
        /// <summary>
        /// 工况状态
        /// </summary>
        public string Status { get; set; }
        /// <summary>
        /// 工况测试ID/等同挡位换算20个
        /// </summary>
        public string TestID { get; set; }
        /// <summary>
        /// 噪音最大值
        /// </summary>
        public int NoiseMax { get; set; } = 0;
        /// <summary>
        /// 噪音最小值
        /// </summary>
        public int NoiseMin { get; set; } = 0;
        /// <summary>
        /// 噪音平均值
        /// </summary>
        public int NoiseAvg { get; set; } = 0;
        /// <summary>
        /// 噪音峰值
        /// </summary>
        public int NoisePeak { get; set; } = 0;
        /// <summary>
        /// 振幅峰值
        /// </summary>
        public int VibrationPeak { get; set; } = 0;
        /// <summary>
        /// 振幅平均值
        /// </summary>
        public int VibrationAvg { get; set; } = 0;
        /// <summary>
        /// 振幅最小值
        /// </summary>
        public int VibrationMin { get; set; } = 0;
        /// <summary>
        /// 原始报文字符
        /// </summary>
        public string DataStr { get; set; } = string.Empty;
    }
    public class ChannelData
    {
        public string Channel { get; set; }
        public string Result { get; set; }
        public string Data { get; set; }
        public string UpperLimit { get; set; }
        public string Max_Checked_Single_Value { get; set; }

    }

    public class NVHCHData
    {
        /// <summary>
        /// 时间
        /// </summary>
        public string DT { get; set; }
        /// <summary>
        /// 总结果
        /// </summary>
        public string Reult { get; set; }
        /// <summary>
        /// SN
        /// </summary>
        public string SN { get; set; }
        /// <summary>
        /// 工况ID
        /// </summary>
        public string TestID { get; set; }
        /// <summary>
        /// 声压曲线-CH1
        /// </summary>
        public string CH1DBLine { get; set; }
        /// <summary>
        /// 声压曲线-CH2
        /// </summary>
        public string CH2DBLine { get; set; }
        /// <summary>
        /// 振动曲线-CH3
        /// </summary>
        public string CH3VibrationLine { get; set; }
        /// <summary>
        /// 振动曲线-CH4
        /// </summary>
        public string CH4VibrationLine { get; set; }

        /// <summary>
        /// 声压平均值-CH1
        /// </summary>
        public string CH1DBAVG { get; set; }
        /// <summary>
        /// 声压平均值-CH2
        /// </summary>
        public string CH2DBAVG { get; set; }
        /// <summary>
        /// 振动平均值-CH3
        /// </summary>
        public string CH3VibrationAVG { get; set; }
        /// <summary>
        /// 振动平均值-CH4
        /// </summary>
        public string CH4VibrationAVG { get; set; }
        /// <summary>
        /// 声压最大值-CH1
        /// </summary>
        public string CH1DBMaxResult { get; set; }
        public string CH1DBMax { get; set; }
        /// <summary>
        /// 声压最大值-CH2
        /// </summary>
        public string CH2DBMaxResult { get; set; }
        public string CH2DBMax { get; set; }
        /// <summary>
        /// 振动最大值-CH3
        /// </summary>
        public string CH3VibrationMaxResult { get; set; }
        public string CH3VibrationMax { get; set; }
        /// <summary>
        /// 振动最大值-CH4
        /// </summary>
        public string CH4VibrationMaxResult { get; set; }
        public string CH4VibrationMax { get; set; }

    }
}
/*
 *
 *\00\00\00\06$A#SN:123242;TEST:2234
 *[2025-10-24 17:42:28.213] [发 127.0.0.1:52773 To 127.0.0.1:8011]  [ASCII]  Bytes Length: 7
\00\00\00\06$A#
[2025-10-24 17:42:30.325] [收 127.0.0.1:8011 To 127.0.0.1:52773]  [ASCII]  Bytes Length: 14
\00\00\00\0A$A^0^OK#\0D\0A
[2025-10-24 17:42:30.327] [收 127.0.0.1:8011 To 127.0.0.1:52773]  [ASCII]  Bytes Length: 152
\00\00\00\94$^data^\0D\0ATransmit Identification:SN\0D\0AData Info:\CD\A8\D3\C3\D7\D6\B7\FB\B4\AE\B4\A6\C0\ED-SN-Processed String\0D\0ATest Result:Not Evaluated\0D\0AData:\0D\0A{\0A123242\0A}\0D\0ALimit:\0D\0A{\0ANone\0A}\0D\0A#
[2025-10-24 17:43:06.250] [收 127.0.0.1:8011 To 127.0.0.1:52773]  [ASCII]  Bytes Length: 182
\00\00\00\B2$^data^\0D\0ATransmit Identification:01\0D\0AData Info:\BC\EC\B2\E9\C7\FA\CF\DF \C9\F9\D1\B9-\C9\F9\D1\B9\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH1_Max_Checked Single Value\0D\0ATest Result:Not Evaluated\0D\0AData:\0D\0A{\0A77.444470\0A}\0D\0ALimit:\0D\0A{\0ANone\0A}\0D\0A#
[2025-10-24 17:43:06.257] [收 127.0.0.1:8011 To 127.0.0.1:52773]  [ASCII]  Bytes Length: 362
\00\00\00\B1$^data^\0D\0ATransmit Identification:03\0D\0AData Info:\BC\EC\B2\E9\C7\FA\CF\DF \D5\F1\B6\AF-\D5\F1\B6\AF\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH3_Max_Checked Single Value\0D\0ATest Result:Not Evaluated\0D\0AData:\0D\0A{\0A0.011688\0A}\0D\0ALimit:\0D\0A{\0ANone\0A}\0D\0A#\00\00\00\B1$^data^\0D\0ATransmit Identification:04\0D\0AData Info:\BC\EC\B2\E9\C7\FA\CF\DF \D5\F1\B6\AF-\D5\F1\B6\AF\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH4_Max_Checked Single Value\0D\0ATest Result:Not Evaluated\0D\0AData:\0D\0A{\0A0.018339\0A}\0D\0ALimit:\0D\0A{\0ANone\0A}\0D\0A#
[2025-10-24 17:43:06.377] [收 127.0.0.1:8011 To 127.0.0.1:52773]  [ASCII]  Bytes Length: 31
\00\00\00\1B$A_over,Status:'OK'^0^OK#\0D\0A





[2025-10-24 17:52:58.414] [发 127.0.0.1:63103 To 127.0.0.1:8011]  [ASCII]  Bytes Length: 7
\00\00\00\06$A#
[2025-10-24 17:53:11.613] [收 127.0.0.1:8011 To 127.0.0.1:63103]  [ASCII]  Bytes Length: 14
\00\00\00\0A$A^0^OK#\0D\0A
[2025-10-24 17:53:11.615] [收 127.0.0.1:8011 To 127.0.0.1:63103]  [ASCII]  Bytes Length: 150
\00\00\00\92$^data^\0D\0ATransmit Identification:SN\0D\0AData Info:\CD\A8\D3\C3\D7\D6\B7\FB\B4\AE\B4\A6\C0\ED-SN-Processed String\0D\0ATest Result:Not Evaluated\0D\0AData:\0D\0A{\0A2342\0A}\0D\0ALimit:\0D\0A{\0ANone\0A}\0D\0A#
[2025-10-24 17:53:45.058] [收 127.0.0.1:8011 To 127.0.0.1:63103]  [ASCII]  Bytes Length: 190
\00\00\00\BA$^data^\0D\0ATransmit Identification:01\0D\0AData Info:\BC\EC\B2\E9\C7\FA\CF\DF \C9\F9\D1\B9-\C9\F9\D1\B9\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH1_Max_Checked Single Value\0D\0ATest Result:Fail\0D\0AData:\0D\0A{\0A98.535000\0A}\0D\0ALimit:\0D\0A{\0AUpper Limit:\090.000000\0A}\0D\0A#
[2025-10-24 17:53:45.060] [收 127.0.0.1:8011 To 127.0.0.1:63103]  [ASCII]  Bytes Length: 378
\00\00\00\B9$^data^\0D\0ATransmit Identification:03\0D\0AData Info:\BC\EC\B2\E9\C7\FA\CF\DF \D5\F1\B6\AF-\D5\F1\B6\AF\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH3_Max_Checked Single Value\0D\0ATest Result:Fail\0D\0AData:\0D\0A{\0A6.607339\0A}\0D\0ALimit:\0D\0A{\0AUpper Limit:\090.000000\0A}\0D\0A#\00\00\00\B9$^data^\0D\0ATransmit Identification:04\0D\0AData Info:\BC\EC\B2\E9\C7\FA\CF\DF \D5\F1\B6\AF-\D5\F1\B6\AF\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH4_Max_Checked Single Value\0D\0ATest Result:Fail\0D\0AData:\0D\0A{\0A4.702216\0A}\0D\0ALimit:\0D\0A{\0AUpper Limit:\090.000000\0A}\0D\0A#
[2025-10-24 17:53:45.168] [收 127.0.0.1:8011 To 127.0.0.1:63103]  [ASCII]  Bytes Length: 242
\00\00\00\EE$A_over^Result:'NG',Status:'NG',\BC\EC\B2\E9\C7\FA\CF\DF \C9\F9\D1\B9-\C9\F9\D1\B9\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH1_Max_Checked Single Value:'NG',\BC\EC\B2\E9\C7\FA\CF\DF \D5\F1\B6\AF-\D5\F1\B6\AF\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH3_Max_Checked Single Value:'NG',\BC\EC\B2\E9\C7\FA\CF\DF \D5\F1\B6\AF-\D5\F1\B6\AF\C7\FA\CF\DF\D7\EE\B4\F3\D6\B5\BC\C6\CB\E3-CH4_Max_Checked Single Value:'NG'^OK#\0D\0A

 * */